﻿using System;
using System.Collections.Generic;
using System.Globalization;
using System.Security.Cryptography;
using System.Text;
using System.Web;

namespace PageAdmin.Utils
{

    /// <summary>
    /// 阿里云签名
    /// </summary>
    internal class AliYunSmsSign
    {
        private AliYunSmsSetting _AliYunSmsSetting;

        public AliYunSmsSign(AliYunSmsSetting aliYunSmsSetting)
        {
            _AliYunSmsSetting = aliYunSmsSetting;
        }
        
        public string GetApi(string phoneNumbers,string templateCode, string templateParamsJson)
        {

            Dictionary<string, string> dictionary = new Dictionary<string, string>();


            //string gmtTime = DateTime.UtcNow.ToString("yyyy-MM-dd'T'HH:mm:ss'Z'");
            string gmtTime= DateTime.Now.ToUniversalTime().ToString("yyyy-MM-dd'T'HH:mm:ss'Z'", CultureInfo.CreateSpecificCulture("en-US"));


            dictionary.Add("AccessKeyId", _AliYunSmsSetting.AccessKeyId);
            dictionary.Add("Action", "SendSms");
            dictionary.Add("Format", "XML");
            dictionary.Add("OutId", "");
            dictionary.Add("PhoneNumbers", phoneNumbers);
            dictionary.Add("RegionId", "cn-hangzhou");
            dictionary.Add("SignName", _AliYunSmsSetting.SignName);
            dictionary.Add("SignatureMethod", "HMAC-SHA1");
            dictionary.Add("SignatureNonce", Guid.NewGuid().ToString("N"));
            dictionary.Add("SignatureVersion", "1.0");
            dictionary.Add("TemplateCode", templateCode);
            dictionary.Add("TemplateParam", templateParamsJson); // "{\"customer\":\"test\"}"
            dictionary.Add("Timestamp", gmtTime);
            dictionary.Add("Version", "2017-05-25");

            //3,去除重名
            if (dictionary.ContainsKey("Signature"))
            {
                dictionary.Remove("Signature");
            }

            //4,排序
            //Dictionary<string, string> dictionarys = dictionary.OrderBy(c => c.Key).ToDictionary(product => product.Key, product => product.Value);


            // 5. 构造待签名的字符串
            StringBuilder sb= new StringBuilder();
           foreach(var keyvaluePair in dictionary)
            {
                string key = keyvaluePair.Key;
                sb.Append("&").Append(SpecialUrlEncode(key)).Append("=").Append(SpecialUrlEncode(keyvaluePair.Value));
            }

            string sortedQueryString = sb.ToString().Substring(1);// 去除第一个多余的&符号
            StringBuilder stringToSign = new StringBuilder();
            stringToSign.Append("GET").Append("&");
            stringToSign.Append(SpecialUrlEncode("/")).Append("&");
            stringToSign.Append(SpecialUrlEncode(sortedQueryString));
            string sign = SignString(_AliYunSmsSetting.AccessKeySecret + "&", stringToSign.ToString());
            // 6. 签名最后也要做特殊URL编码
            string signature = SpecialUrlEncode(sign);
            string api = "http://dysmsapi.aliyuncs.com/?Signature=" + signature + "&" + sortedQueryString;
            return api;
        }


        public String SignString(String accessSecret,String source)
        {
            using (var algorithm = KeyedHashAlgorithm.Create("HMACSHA1"))
            {
                algorithm.Key = Encoding.UTF8.GetBytes(accessSecret.ToCharArray());
                return Convert.ToBase64String(algorithm.ComputeHash(Encoding.UTF8.GetBytes(source.ToCharArray())));
            }
        }

        private static String SpecialUrlEncode(string value)
        {
            return HttpUtility.UrlEncode(value, Encoding.UTF8).Replace("+", "%20").Replace("*", "%2A").Replace("%7E", "~");
        }
    }

}